import React, { memo, useState, useEffect } from 'react';
import { Form, Input, Modal, Row, Col, message, Select, Typography, Switch, Tooltip, Button } from 'antd';
import classNames from 'classnames';
import IconFont from '@/components/IconFont';

import LimitInput from '@/components/LimitInput';

import { onEditSalaryItemSimple, queryDictList } from '@/services/salaryManage/salaryCalculate';
import { COMMON_NAME } from '@/pages/SalaryManage/utils';
import tabMessageUtil from '@/pages/SalaryManage/utils/tabMessageUtil';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import styles from '../../SalaryMainAdd/index.less';

const { Option } = Select;
const SALARY_TYPE_OPTIONS = 'salaryTypeOptions';
const DICT_NAME_LIST = [SALARY_TYPE_OPTIONS];

const TemplateSalaryModal = ({
    visible,
    onChange,
    onCancel,
    form,
    itemType = 'add',
    disabled = false,
    editData = {},
    currentOrgCode
}) => {
    const { getFieldDecorator, validateFields } = form;
    const [loading, setLoading] = useState(false);
    const formItemLayout = {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 7 }
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 17 }
        }
    };
    const [modalDictList, setModalDictList] = useState({});
    const getDictList = (key, condition) => {
        if (condition) {
            return modalDictList[key]
                ? modalDictList[key].filter(item => item.filter && item.filter.indexOf(condition) !== -1)
                : [];
        }
        return modalDictList[key] || [];
    };
    const getModalDictList = async () => {
        try {
            const confTypes = DICT_NAME_LIST.join(',');
            const { code, data = {} } = await queryDictList(confTypes);
            if (code === 10000) {
                console.log('modal数据字典列表', data);
                setModalDictList(data);
            }
        } catch (e) {
            console.log('获取modal中的字段列表失败', e);
        }
    };
    const onAdd = async values => {
        try {
            setLoading(true);
            const params = {
                ...editData,
                organizationCode: currentOrgCode,
                ...values
            };
            const { code, msg = '操作失败，请检查！' } = await onEditSalaryItemSimple(params);
            if (code === 10000) {
                tabMessageUtil.noticeRefreshByPathname('/finance/salary/salarytemplateedit');
                onChange();
                message.success('操作成功！');
            } else {
                message.error(msg);
            }
            setLoading(false);
        } catch (e) {
            console.log(e);
        }
    };
    useEffect(() => {
        getModalDictList().then();
    }, []);

    // 新资类型下拉选项
    const getSalaryTypeOptions = salaryType =>
        getDictList(SALARY_TYPE_OPTIONS).filter(option => {
            const filterArray = option?.filter || [];

            return filterArray.some(fil => String(fil) === String(salaryType));
        });

    return (
        <Modal
            title={itemType === 'add' ? '编辑薪资加项' : '编辑薪资减项'}
            visible={visible}
            width={480}
            confirmLoading={loading}
            className={classNames(styles.editSalaryMainModal, styles.templateSalaryModal)}
            onOk={() => {
                validateFields((err, values) => {
                    if (!err) {
                        onAdd(values);
                    }
                });
            }}
            onCancel={onCancel}
            destroyOnClose
        >
            <Form {...formItemLayout}>
                <Row>
                    <Col span={24}>
                        <div style={{ textAlign: 'left', marginBottom: '16px' }}>
                            <Typography.Text type="secondary">仅支持以下内容进行编辑</Typography.Text>
                        </div>
                    </Col>
                </Row>
                {getFieldDecorator('parentId', {
                    initialValue: editData.parentId
                })(<Input type="hidden" />)}
                <Form.Item label="上级薪资项">
                    {getFieldDecorator('parentName', {
                        initialValue: editData.parentName,
                        rules: [
                            {
                                required: true,
                                message: '请输入上级薪资项名称!'
                            }
                        ]
                    })(<Input disabled={disabled} maxLength={20} />)}
                </Form.Item>
                <Form.Item label="薪资要素">
                    {getFieldDecorator('itemName', {
                        initialValue: editData.itemName,
                        rules: [
                            { required: true, message: '请输入新增薪资要素名称' },
                            {
                                max: 100,
                                message: '不能超过100个字符'
                            },
                            {
                                pattern: COMMON_NAME.REG,
                                message: COMMON_NAME.MESSAGE
                            }
                        ]
                    })(<Input placeholder="请输入新增薪资要素名称" maxLength={100} />)}
                </Form.Item>
                <Form.Item
                    label={
                        <span>
                            薪资类型&nbsp;
                            <Tooltip
                                title="薪资类型的选择不影响薪资计算，只影响后续报表分析统计"
                                overlayStyle={{ maxWidth: 'unset' }}
                            >
                                <Button className={salaryStyle.iconBtn}>
                                    <IconFont type="question-circle" />
                                </Button>
                            </Tooltip>
                        </span>
                    }
                >
                    {getFieldDecorator('salaryType', {
                        initialValue: editData.salaryType,
                        rules: [
                            {
                                required: true,
                                message: '请选择薪资类型!'
                            }
                        ]
                    })(
                        <Select placeholder="请选择" disabled={disabled}>
                            {getSalaryTypeOptions(editData.itemType).map(item => (
                                <Option value={item.key} key={item.value}>
                                    {item.value}
                                </Option>
                            ))}
                        </Select>
                    )}
                </Form.Item>
                {itemType === 'add' ? (
                    <Form.Item label="是否Offer字段">
                        {getFieldDecorator('isOffer', {
                            initialValue: !!editData.isOffer || false,
                            valuePropName: 'checked'
                        })(<Switch disabled={disabled} />)}
                    </Form.Item>
                ) : null}
                <Form.Item label="备注说明">
                    {getFieldDecorator('remark', {
                        initialValue: editData.remark
                    })(<LimitInput maxLength={500} area showNumber />)}
                </Form.Item>
            </Form>
        </Modal>
    );
};
export default memo(Form.create({ name: 'templateSalaryModal' })(TemplateSalaryModal));
